<?php
require 'Buyer/ActionRegistrationBuyer.php';
require 'Buyer/ActionEditBuyer.php';
require 'Buyer/ActionLoginBuyer.php';
require_once APPLICATION_PATH.'\misc\exceptionHandler.php';
require_once APPLICATION_PATH.'\misc\sessionController.php';
require_once APPLICATION_PATH.'\misc\Paging.php';
require_once APPLICATION_PATH.'\misc\additional.php';
class BuyerController extends Zend_Controller_Action
{

    private $controller = 'Buyer';

    private $classname = 'BuyerController.php';

    private $paramName = array(
        'Super',
        'Admin'
        );

    public function init()
    {
        $sessionController=new sessionController();
        $this->view->sessioncontroller = $sessionController;
    }

    public function indexAction()
    {
        $this->view->message = $this->_helper->_flashMessenger->getMessages();
    }

    public function registerAction()
    {
    $this->_helper->layout->disableLayout();
    $this->_helper->layout->setLayout('registerlayout');
     try{
        $this->view->errormessage;
        //Initialize actionRegistrationBuyer
        $actionBuyer = new Application_Controllers_Buyer_ActionRegistrationBuyer();

        //Initialize Form
        $forms = new Application_Form_Buyer_RegistrationBuyer();
        //set Label for every instance
        $forms->username->setLabel('Username');
        $forms->password->setLabel('Password');
        $forms->email->setLabel('Email');
        $forms->name->setLabel('Nama');
        $forms->gender->setLabel('Jenis Kelamin');
        $forms->date_birth->setLabel('Tanggal Lahir');
        $forms->address->setLabel('Alamat');
        $forms->home_phone->setLabel('Telepon Rumah');
        $forms->mobile_phone->setLabel('HandPhone');
        $forms->submit->setLabel('Save');
        $forms->reset->setLabel('Clear');
        $forms->repassword->setLabel('Re-enter Password');
        //$form->avatar->setLabel("Upload avatar");
        //change avatar name'
       
        //Initialize Form to Display
        $formDisplay = new Application_Form_Display();
        //Adding Elements to Form Display
        $formDisplay->addElements(array($forms->buyerID,$forms->username,
                                        $forms->password,$forms->repassword,
                                        $forms->email,$forms->name,$forms->gender,
                                        $forms->date_birth,$forms->address,$forms->city,
                                        $forms->province,$forms->zip,$forms->home_phone,
                                        $forms->mobile_phone/*,$forms->captcha*/,$forms->submit,$forms->reset
                                         ));
        $this->view->form = $formDisplay;
        if ($this->getRequest()->isPost()) {
         $formData = $this->getRequest()->getPost();
            if ($formDisplay->isValid($formData)) {
                //get avatar path
               //$path='C:\xampp\htdocs\bitz-plaza\public\images\avatar\'.$form->getValue('username');
               //Setting Destination for avatar
               //echo "path :".$path ;
               
                //$form->avatar->setDestination($path);
               //  $form->avatar->addFilter('Rename', 'C:\xampp\htdocs\bitz-plaza\public\images\avatar\ '
                 //       .$form->getValue('username').'.jpg', $form->avatar);
                if($actionBuyer->PreRegistration($formDisplay)){
                        $actionBuyer->onRegistration($formDisplay);
                        $this->_helper->_flashMessenger->addMessage('Pendaftaran berhasil, mohon cek email anda untuk aktivasi akun');

                         mkdir(realpath('.').'\users\\'.$formDisplay->getValue('username'));
                        mkdir(realpath('.').'\\users\\'.$formDisplay->getValue('username').'\\avatar\\');
                        $this->view->done=true;
                        $this->view->message="Terima kasih telah mendaftar di Bitz-Plaza, Link aktivasi telah terkirim ke ".$formDisplay->getValue('email').
                                " Mohon aktivasi akun anda untuk menikmati layanan Bitz-Plaza";
                        //$this->helper->redirector
                        //($this->url(array("controller" => "index", "action" => "index")));
                }else{
                  $this->view->errormessage=$actionBuyer->wrongMessage;
                  $formDisplay->populate($formData);
                }
            } else {
               $formDisplay->populate($formData);
            }
        }
     }catch(Zend_Exception $e){
           //initialize applog
           $exceptionHandler = new exceptionHandler();
           $exceptionHandler->addLog($e, $this->classname);          
    
    
     }
    }
    

    public function loginAction()
    {   
        $sessionController = new sessionController();


        $this->_helper->layout->disableLayout();
        $this->view->errormessage="";
        
        //Initialize actionRegistrationBuyer
        $actionBuyer = new Application_Controllers_Buyer_ActionLoginBuyer();
        $buyer = new Application_Model_DbTable_Buyers();
        //Initialize Form
        $form = new Application_Form_Buyer_Buyer();
        //set Label for every instance
        $form->username->setLabel('Username');
        $form->password->setLabel('Password');
        $form->submit->setLabel('Masuk');
        $form->reset->setLabel('Reset');
        //change avatar name'
        //
        //Initialize Form to Display
        $formDisplay = new Application_Form_Display();
        //Adding Elements to Form Display
        $formDisplay->addElements(array($form->username,
                                        $form->password,$form->submit));
        $this->view->form = $formDisplay;
        if ($this->getRequest()->isPost()) {
             
            $formData = $this->getRequest()->getPost();
            if ($formDisplay->isValid($formData)) {
                
                if($actionBuyer->preLogin($formDisplay)){
                  $buyer=new Application_Model_DbTable_Buyers();

                  $sessionController = new sessionController();
                  $sessionController->setBuyer();
                  $params=array('role'=>'buyer','username'=>$formDisplay->getValue('username')
                          ,'id'=>$buyer->getBuyerId($formDisplay->getValue('username')),
                                  'logId'=>1);
                  $sessionController->initialize($params);
                  //$request = new Zend_Controller_Request_Abstract();
                 
                  $this->_helper->redirector('index','FrontPage');
                  }else{
                  $this->view->errormessage=$actionBuyer->wrongMessage;
                  $formDisplay->populate($formData);
                }

              // $form->populate($formData);
            }else{
               
                $formDisplay->populate($formData);
            }    
        
        }
    }
    

    public function editAction()
    {
     try{
        $id = $this->_getParam('id', 0);
        $sessionController=new sessionController();

        if($sessionController->checkSessionAdmin($this->paramName)){
        $buyer = new Application_Model_DbTable_Buyers();
        $row = $buyer->getBuyer($id);
        $form = new Application_Form_Buyer_Buyer();
        $form->submit->setLabel('Update');
                $form->username->setLabel('Username');
        $form->password->setLabel('Password');
        $form->email->setLabel('Email');
        $form->name->setLabel('Nama');
        $form->gender->setLabel('Jenis Kelamin');
        $form->date_birth->setLabel('Tanggal Lahir')
                ->SetAttrib('readonly','true');
        $form->address->setLabel('Alamat');
        $form->home_phone->setLabel('Telepon Rumah');
        $form->mobile_phone->setLabel('HandPhone');
        $form->active->setLabel('Status');
        $form->reset->setLabel('Clear');

                //Create role DB
        $form->gender->setLabel("Jenis Kelamin")
                        ->setValue($row['gender'],$row['gender']);
        $formDisplay = new Application_Form_Display();
        $formDisplay->addElements(array($form->buyer_id,$form->name,$form->address,$form->city,
                                  $form->province,$form->zip,
            $form->mobile_phone,$form->home_phone,$form->gender,$form->date_birth,$form->active,
            $form->submit,$form->reset));
        $this->view->form = $formDisplay;

        if($this->getRequest()->isPost()){
            $postData = $this->getRequest()->getPost();
            //Validate input data
            if($formDisplay->isValid($postData)){
                
                $buyerController = new Application_Controllers_Buyer_ActionEditBuyer();
                $buyerController->onEdit($id,$formDisplay);
                
                $this->_helper->_flashMessenger->addMessage("Data pembeli ".$row["name"]." telah berhasil diupdate");
                $this->_helper->redirector('list');
                 
            }else{
                $formDisplay->populate($postData);
            }
        }else {
            if ($id > 0) {
                $this->view->username= $row['username'];
                $formDisplay->populate($buyer->getBuyer($id));
            }
        }
        }else{
            $this->_helper->redirector('login','admin');
        }
    }catch(Zend_Exception $e){
           //initialize applog
        echo $e->getMessage();
           $exceptionHandler = new exceptionHandler();
           $exceptionHandler->addLog($e, $this->classname);   
     
    
    
    
    
    }
    
    }

    public function removeAction()
    {
        $sessionController=new sessionController();
        if($sessionController->checkSessionAdmin($this->paramName)){
                $id = $this->_getParam('id', 0);
                $buyer=new Application_Model_DbTable_Buyers();
                $row=$buyer->getBuyer($id);
                $buyer->deleteBuyer($id);
                $actionLog = new Application_Model_DbTable_Actionlog();
                $actionLog->addActionLog($sessionController->getSessionLogId(),
                                            "[".$_SERVER['REMOTE_ADDR']
                                             ."][".$sessionController->getSessionUsername()."]".
                                             "[".$sessionController->getSessionRole()."] Hapus Pelanggan ".
                                             "Name : ".$row['name']
                                             ." Username :".$row['username']."");
                 $this->_helper->_flashMessenger->addMessage("Data pembeli ".$row["name"]." telah berhasil dihapus");
                $this->_helper->redirector('list');                
              }else{
                $this->_helper->redirector('list');
              }     
    }

    public function listAction()
    {
                // action body
       try{
        $this->view->additional = new Additional();
        $sessionController=new sessionController();
        $paging = new Paging();
        $buyer = new Application_Model_DbTable_Buyers();
        $this->view->message = $this->_helper->_flashMessenger->getMessages();
        if($sessionController->checkSessionAdmin($this->paramName)){
                $page=  $this->_getParam('page', 1);
                $order=  $this->_getParam('order', "buyer_id");
                $method = $this->_getParam('method', "asc");
                $name = strtolower($this->_getparam('name',''));
                
                $where="";
                if($name!=""){
                    $where = "and c.name like '%".$name."%'";
                }
                $this->view->buyers = $buyer->getAll(' c.deleted <>1 '.$where,$order,$method,$page, Paging::$number);
                $this->view->page=$page;
                $this->view->order=$order;
                $this->view->premethod=$method;
                if($method=='asc'){
                    $this->view->method='desc';
                }else{
                    $this->view->method='asc';
                }
                
                $this->view->name=$name;
                $this->view->totalPages=  Paging::totalPages($buyer->countRows($where));
                $this->view->back=  $paging->back($this->controller, 'list', $page, $order, $method,$name);
                $this->view->next=  $paging->next($this->controller, 'list',
                            $this->view->totalPages, $page, $order, $method,$name);
                $this->view->current = $paging->current($this->controller, 'list',
                        $this->view->totalPages, $page, $order, $method,$name);}else{
                $this->_helper->redirector('login','admin');
            }
        }catch(Zend_Exception $e){
           $exceptionHandler = new exceptionHandler();
           $exceptionHandler->addLog($e, $this->classname);}
    
    }

    public function detailAction()
    {
     try{
        $this->view->additional = new Additional();
        $sessionController=new sessionController();

        if($sessionController->checkSessionAdmin($this->paramName)){
                $id = $this->_getParam('id', 0);
                $buyer = new Application_Model_DbTable_Buyers();
                $this->view->method='asc';
                //get record by admin_id                
                $this->view->buyer = $buyer->getBuyer($id);
                
             }else{
                $this->_helper->redirector('login','admin');
            }
        }catch(Zend_Exception $e){
           $exceptionHandler = new exceptionHandler();
           $exceptionHandler->addLog($e, $this->classname);          
        
    
    
    
    
        }
    
    }

    public function summaryAction()
    {
       try{
        $sessionController=new sessionController();

        if($sessionController->checkSessionAdmin($this->paramName)){
                $buyer = new Application_Model_DbTable_Buyers();
                $this->view->hit5=$buyer->getHighHit(5);
                $this->view->buy5=$buyer->getHighBuy(5);}else{
                
                //set redirector to another controller
                $request = $this->getRequest();
                $this->_helper->redirector('login','admin');
            }
        }catch(Zend_Exception $e){
           $exceptionHandler = new exceptionHandler();
           $exceptionHandler->addLog($e, $this->classname);
    
    
    
    
    
    
        }
    }

    public function searchAction()
    {
        $this->view->additional = new Additional();
        $this->_helper->layout->disableLayout();

    $this->_helper->layout->disableLayout();
     try{
        $paging = new Paging();
        $buyer = new Application_Model_DbTable_Buyers();
        $sessionController=new sessionController();
        
        if($sessionController->checkSessionAdmin($this->paramName) ){
                
                $order=  $this->_getParam('order', "buyer_id");
                $method = $this->_getParam('method', "asc");
                $name = strtolower($this->_getparam('name',''));
                $where="";
                if($name!=""){
                    $where = " and c.username like '%".$name."%'";
                }
                $this->view->buyers = $buyer->getAll('c.deleted <>1'.$where,$order,$method,1, Paging::$number);
               
                $this->view->order=$order;
                $this->view->premethod=$method;
                if($method=='asc'){
                    $this->view->method='desc';
                }else{
                    $this->view->method='asc';
                }

                $this->view->name=$name;
                $this->view->totalPages=  Paging::totalPages($buyer->countRows($where));
                $this->view->back=  $paging->back($this->controller, 'list', 1, $order, $method,$name);
                $this->view->next=  $paging->next($this->controller, 'list',
                            $this->view->totalPages, 1, $order, $method,$name);
                $this->view->current = $paging->current($this->controller, 'list',
                        $this->view->totalPages, 1, $order, $method,$name);
                }else{
                    $this->_helper->redirector('login','admin');
                }
      }catch(Zend_Exception $e){
           $exceptionHandler=new exceptionHandler();
           $exceptionHandler->addLog($e,$this->classname); 
    
    
    
    
      }
    
    }

    public function profileAction()
  { 

                 $this->_helper->layout->disableLayout();
        $sessionController=new sessionController();
        $this->view->sessioncontroller = $sessionController;
        $this->view->transactions = new Application_Model_DbTable_Transaction();
        /* Initialize action controller here */

        // action body
        $sessionController = new sessionController();
        $cat_db = new Application_Model_DbTable_Category();
        $this->view-> categories = $cat_db->fetchAll();
        if($sessionController->checkSessionBuyer()){
            $this->view->contentcontroller='FrontPage';
            $this->view->contentaction='afterlogin';
            $sessionController->setBuyer();
            $this->view->buyerId=$sessionController->getSessionId();
            $this->view->rightlabel = "Pembeli";
        }else{
            $this->view->contentcontroller='buyer';
            $this->view->contentaction='login';
            $this->view->buyerId=0;
            $this->view->rightlabel = "Login Pembeli";
        }
        $this->view->transaction = new Application_Model_DbTable_Transaction();
        $this->_helper->layout->setLayout('frontlayout');
        $buyer = new Application_Model_DbTable_Buyers();
        $this->view->message=$this->_helper->_flashMessenger->getMessages();
        $sessionController = new sessionController();
        $sessionController->setBuyer();
        $username = $sessionController->getSessionUsername();
        $this->view->username=$sessionController->getnameSpace();
        $this->view->buyer=$buyer->fetchRow("username='$username'");
        if($this->view->buyer['avatar']==null){
            $this->view->image="/images/avatar/none.png";
        }else{
            $this->view->image="/users/".$this->view->buyer['username']."/avatar/".$this->view->buyer['avatar'];
        }

    }
    
    public function editpasswordAction()
    {
        // action body
    }

    public function editavatarAction()
    {
                 $this->_helper->layout->disableLayout();
        $sessionController=new sessionController();
        $this->view->sessioncontroller = $sessionController;
        $this->view->transactions = new Application_Model_DbTable_Transaction();
        /* Initialize action controller here */

        // action body
        $sessionController = new sessionController();
        $cat_db = new Application_Model_DbTable_Category();
        $this->view-> categories = $cat_db->fetchAll();
        if($sessionController->checkSessionBuyer()){
            $this->view->contentcontroller='FrontPage';
            $this->view->contentaction='afterlogin';
            $sessionController->setBuyer();
            $this->view->buyerId=$sessionController->getSessionId();
            $this->view->rightlabel = "Pembeli";
        }else{
            $this->view->contentcontroller='buyer';
            $this->view->contentaction='login';
            $this->view->buyerId=0;
            $this->view->rightlabel = "Login Pembeli";
        }
        $this->view->transaction = new Application_Model_DbTable_Transaction();
        $this->_helper->layout->setLayout('frontlayout');
        $id=$this->_getParam('id',0);
        $buyers = new Application_Model_DbTable_Buyers();
        $buyer = $buyers->fetchRow('buyer_id='.$id);

        $formDisplay=new Application_Form_Display();
        $form = new Application_Form_Buyer_Buyer();
       // echo "C:\xampp\htdocs\bitz-plaza\public\users\".$buyer['username']."\avatar\";
        $form->avatar->setLabel('Pilih Avatar:')
                     ->setDestination(realpath('.')."\\users\\".$buyer['username']."\\avatar\\");

        
        $form->submit->setLabel('Ubah Avatar');
        $formDisplay->addElements(array($form->avatar,$form->submit));
        $this->view->form = $formDisplay;

        if($this->getRequest()->isPost()){
            $postData = $this->getRequest()->getPost();
            //Validate input data
            if($formDisplay->isValid($postData)){
                $data=array('avatar'=>$formDisplay->getValue('avatar'));
                $buyers->update($data, 'buyer_id='.$id);
                $this->_helper->_flashMessenger->addMessage("Avatar telah terganti");
                $this->_helper->redirector('profile');

            }else{
                $formDisplay->populate($postData);
            }
    
        }
    
    }

    public function editdetailsAction()
    {
        // action body
    }

    public function displayTransactionAction()
    {
         $this->_helper->layout->disableLayout();
        $sessionController=new sessionController();
        $this->view->sessioncontroller = $sessionController;
        $this->view->transactions = new Application_Model_DbTable_Transaction();
        /* Initialize action controller here */

        // action body
        $sessionController = new sessionController();
        $cat_db = new Application_Model_DbTable_Category();
        $this->view-> categories = $cat_db->fetchAll();
        if($sessionController->checkSessionBuyer()){
            $this->view->contentcontroller='FrontPage';
            $this->view->contentaction='afterlogin';
            $sessionController->setBuyer();
            $this->view->buyerId=$sessionController->getSessionId();
            $this->view->rightlabel = "Pembeli";
        }else{
            $this->view->contentcontroller='buyer';
            $this->view->contentaction='login';
            $this->view->buyerId=0;
            $this->view->rightlabel = "Login Pembeli";
        }
        $this->view->transaction = new Application_Model_DbTable_Transaction();
        $this->_helper->layout->setLayout('frontlayout');
        $this->view->message = $this->_helper->_flashMessenger->getMessages();
        $this->view->additional = new Additional();
        $paging = new Paging();
        $this->view->transStatus=new Application_Model_DbTable_TransactionStatus();


        if($sessionController->checkSessionBuyer()){
        $this->view->transactions = new Application_Model_DbTable_Transaction();
        $this->view->shop = new Application_Model_DbTable_Shop();
        //$this->view->transaction=$transaction->fetchAll("buyer_id=".$sessionController->getSessionId(),
         //                               " transaction_status_id,last_update,date");
        
                $page=$this->_getParam('page', 1);
                $order=  $this->_getParam('order', "transaction_status_id,tr.last_update,tr.date");
                $method = $this->_getParam('method', "desc");
                $this->view->page=$page;
                $this->view->order=$order;
                $this->view->premethod=$method;
                if($method=='asc'){
                    $this->view->method='desc';
                }else{
                    $this->view->method='asc';
                }

                $totalPages=Paging::totalPages($this->view->transactions->countRows("buyer_id=".$sessionController->getSessionId()));
                $this->view->transaction=$this->view->transactions->getAll(Paging::$number,$page,"buyer_id=".$sessionController->getSessionId(),
                $order,$method);
                $this->view->totalPages= $totalPages;
                $this->view->back=  $paging->back($this->controller, 'display-transaction', $page, $order, $method,"");
                $this->view->next=  $paging->next($this->controller, 'display-transaction',
                            $this->view->totalPages, $page, $order, $method,"");
                $this->view->current = $paging->current($this->controller, 'display-transaction',
                $this->view->totalPages, $page, $order, $method,"");
                
        }else{
            $this->_helper->redirector('index','frontPage');
        
    }
    }
    public function getdetailAction()
    {   $this->_helper->layout->disableLayout();
        $id = $this->_getParam('id', 0);
        $detail = $this->_getParam('detail', '');
        $buyers = new Application_Model_DbTable_Buyers();
        
        
        $buyer=$buyers->fetchRow('buyer_id='.(int)$id);
        if($detail=='address'){
            $this->view->output=$buyer->address;
      
        }
        if($detail=='zip'){
            $this->view->output=$buyer->zip;
   }

        if($detail=='province'){
            $this->view->output=$buyer->province;
        }
        if($detail=='city'){
            $this->view->output=$buyer->city;
        }
        if($detail=='name'){
            $this->view->output=$buyer->name;
        }
    }





    public function logoutAction()
    {
        $sessionController= new sessionController();
        $sessionController->setBuyer();
        $sessionController->logOut();
        $this->_helper->redirector('index','FrontPage');
        //$_redirector = $this->_helper->getHelper("Redirector");
        //$_redirector->gotoUrl('/FrontPage');
    }



}
